package cn.ai.shoes.common.exception.handler;

import cn.ai.shoes.common.exception.ServiceException;
import cn.ai.shoes.common.exception.util.ErrorCode;
import cn.ai.shoes.common.pojo.entity.CommonResult;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import java.util.List;

import static cn.ai.shoes.common.exception.constant.GlobalErrorCodeConstants.*;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理所有异常
     * @param e 异常对象
     * @return 响应结果
     */
    @ExceptionHandler(RuntimeException.class)
    public CommonResult handleException(RuntimeException e) {
        // 打印异常信息
        e.printStackTrace();
        // 响应给前端
        return CommonResult.error(LOCKED);
    }
    /**
     * 处理所有异常
     * @param e 异常对象
     * @return 响应结果
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult handleException(HttpMessageNotReadableException e) {
        // 打印异常信息
        e.printStackTrace();
        // 响应给前端
        return CommonResult.error(BAD_REQUEST);
    }
    /**
     * validation注解异常处理
     * @param ex 异常对象
     * @return 响应结果
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public CommonResult handleValidationException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<String> errors = bindingResult.getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .toList();

        return CommonResult.error(BAD_REQUEST.getCode(), String.join("；", errors));
    }
    /**
     * 空输入异常
     * @param ex 异常对象
     * @return 响应结果
     */
    @ExceptionHandler(NullPointerException.class)
    public CommonResult handleNullPointerException(NullPointerException ex) {
        String msg = ex.getMessage();
        // 响应给前端
        return CommonResult.error(BAD_REQUEST.getCode(), msg);
    }

    /**
     * Service异常处理
     * @param ex 异常对象
     * @return 响应结果
     */
    @ExceptionHandler(ServiceException.class)
    public CommonResult handleServiceException(ServiceException ex) {
        // 获取错误消息
        String message = ex.getMessage();
        
        // 尝试解析为ErrorCode，如果失败则使用默认错误码
        try {
            ErrorCode errorCode = ErrorCode.fromResult(message);
            return CommonResult.error(errorCode);
        } catch (Exception e) {
            // 如果解析失败，使用默认的错误码和消息
            return CommonResult.error(INTERNAL_SERVER_ERROR.getCode(), message);
        }
    }

    /**
     * 权限不足异常
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public CommonResult handleAccessDenied() {
        return CommonResult.error(FORBIDDEN);
    }
}
